package com.lvlian.ge_message

import android.Manifest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.telephony.SmsManager
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.lvlian.ge_message.model.ContactInfo
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

class MainActivity : AppCompatActivity() {

    lateinit var messageContent: EditText
    lateinit var replaceWord: EditText
    lateinit var contactsList: EditText
    lateinit var submitButton: Button
    lateinit var logView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        messageContent = findViewById(R.id.messageContent)
        replaceWord = findViewById(R.id.replaceWord)
        contactsList = findViewById(R.id.contactsList)
        submitButton = findViewById(R.id.submitButton)
        logView = findViewById(R.id.logView)
        submitButton.setOnClickListener { onSubmit() }
    }

    private fun onSubmit() {
        submitButton.requestFocusFromTouch()
        val message = messageContent.text.toString()
        val replace = replaceWord.text.toString()
        val contacts = contactsList.text.toString()
        if (message.isNullOrBlank() || contacts.isNullOrBlank()) {
            showT("请输入短信内容和联系人信息")
            return
        }

        RxPermissions(this)
            .request(Manifest.permission.SEND_SMS)
            .subscribe({
                if (it) sendMessage(message, contacts, replace)
                else showT("获取权限失败")
            }, Consumer { obj: Throwable -> obj.printStackTrace() })
    }

    private fun sendMessage(message: String, contacts: String, replace: String) {
        val manager = SmsManager.getDefault()
        val contactsArray = contacts.split("\n")

        /*Thread(Runnable {
            for (contact in contactsArray) {
                var contactInfo = ContactInfo(contact)
                val sendContent = contactInfo.formatMsg(message, replace)
                manager.sendTextMessage(contactInfo.phoneNumber, null, sendContent, null, null)
                runOnUiThread {
                    logView.append(sendContent)
                    logView.append("\n")
                }
            }
            runOnUiThread {
                showT("发送成功")
            }
        }).start()*/

        Observable.fromIterable(contactsArray)
            .map {
                var contactInfo = ContactInfo(it)
                val sendContent = contactInfo.formatMsg(message, replace)
                manager.sendTextMessage(contactInfo.phoneNumber, null, sendContent, null, null)
                return@map sendContent
            }
            .subscribeOn(Schedulers.single())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { logView.append("正在发送...\n") }
            .doOnTerminate { showT("发送成功") }
            .subscribe({
                logView.append(it)
                logView.append("\n")
            },{
                logView.append("发送异常\n")
            })

    }

    private fun showT(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }
}